import axios from 'axios'
import router from '@/router'

import { ElMessage } from 'element-plus'

// Create axios instance
const service = axios.create({
  baseURL: 'http://localhost:8080/api/v1', // API base URL
  timeout: 50000, // Request timeout
})

// Request interceptor
service.interceptors.request.use(
  (config) => {
    // Add token to header if exists
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    console.error('Request error:', error)
    return Promise.reject(error)
  },
)

// Response interceptor
service.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    console.error('Response error:', error)
    const status = error.response.status
    const data = error.response.data
    switch (status) {
      case 401:
        ElMessage.error(data.message || '登录已过期，请重新登录')
        localStorage.removeItem('token')
        router.push('/login')
        break
      case 403:
        ElMessage.error('没有权限访问此资源')
        break
      case 500:
        ElMessage.error(data.message || '服务器出错')
        break
      default:
        ElMessage.error(data.message || '网络错误或服务器无响应')
    }
    return Promise.reject(error)
  },
)

export default service
